package com.lql.search.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.domain.PageDTO;
import com.lql.api.dto.ItemDTO;
import com.lql.search.domain.po.Item;
import com.lql.search.domain.po.ItemDoc;
import com.lql.search.domain.query.ItemPageQuery;
import com.lql.search.domain.vo.CategoryAndBrand;
import com.lql.search.service.ISearchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@Api(tags = "搜索相关接口")
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
public class SearchController {
    private final ISearchService searchService;

    private final RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(HttpHost.create("http://192.168.44.128:9200"))
    );
    @ApiOperation("搜索商品")
    @GetMapping("/list")
    public PageDTO<ItemDTO> search(ItemPageQuery query) throws IOException {
        /*// 分页查询
        Page<Item> result = searchService.lambdaQuery()
                .like(StrUtil.isNotBlank(query.getKey()), Item::getName, query.getKey())
                .eq(StrUtil.isNotBlank(query.getBrand()), Item::getBrand, query.getBrand())
                .eq(StrUtil.isNotBlank(query.getCategory()), Item::getCategory, query.getCategory())
                .eq(Item::getStatus, 1)
                .between(query.getMaxPrice() != null, Item::getPrice, query.getMinPrice(), query.getMaxPrice())
                .page(query.toMpPage("update_time", false));
        // 封装并返回
        return PageDTO.of(result, ItemDTO.class);*/
        return searchService.searchEs(query);
    }

    @ApiOperation("搜索商品连带的分类和品牌")
    @PostMapping("/filters")
    public CategoryAndBrand searchFilters(@RequestBody ItemPageQuery query) throws IOException {
        return searchService.filters(query);
    }


    @ApiOperation("根据id查询商品")
    @GetMapping("/{id}")
    public ItemDTO queryItemById(@PathVariable("id") Long id) throws IOException {
        // 1.准备Request
        GetRequest request = new GetRequest("items", id.toString());
        // 2.发送请求
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 3.解析结果
        String item = response.getSourceAsString();

        ItemDoc itemDoc = JSONUtil.toBean(item, ItemDoc.class);

        return BeanUtil.copyProperties(itemDoc, ItemDTO.class);
    }
}
